package main

import (
	"context"
	"fmt"
	"net"
	"os"
	"os/signal"
	"syscall"

	"github.com/satori/go.uuid"
	"google.golang.org/grpc"
	"google.golang.org/grpc/health"
	"google.golang.org/grpc/health/grpc_health_v1"

	"oldpackagetest/grpc_test/proto"
	"oldpackagetest/grpclb_test/consul"
)

type Server struct{}

func (s *Server) SayHello(ctx context.Context, request *proto.HelloRequest) (*proto.HelloReply, error) {
	fmt.Println("已调用", request.Name)
	return &proto.HelloReply{
		Message: "hello" + request.Name,
	}, nil
}

func GetFreePort() (int, error) {
	addr, err := net.ResolveTCPAddr("tcp", "localhost:0")
	if err != nil {
		return 0, err
	}
	l, err := net.ListenTCP("tcp", addr)
	if err != nil {
		return 0, err
	}
	defer l.Close()
	return l.Addr().(*net.TCPAddr).Port, nil
}
func main() {
	Port, _ := GetFreePort()
	g := grpc.NewServer()
	//grpc注册方法
	proto.RegisterGreeterServer(g, &Server{})
	lis, err := net.Listen("tcp", fmt.Sprintf("10.231.72.37:%d", Port))

	//注册服务健康检查
	grpc_health_v1.RegisterHealthServer(g, health.NewServer())
	//consul服务注册
	register_client := consul.NewRegistryClient("192.168.10.130", 8500)
	serviceId := fmt.Sprintf("%s", uuid.NewV4())
	err = register_client.Register("10.231.72.37", Port, "user_srv", []string{"srv"}, serviceId)
	if err != nil {
		fmt.Printf("【srv】服务注册失败：%s\n", err.Error())
	} else {
		fmt.Println("【srv】注册成功")
	}
	//运行server
	//启动服务
	go func() {
		err = g.Serve(lis)
		if err != nil {
			panic("failed to start grpc:" + err.Error())
		}
	}()
	//接受终止信号 用于注销consul服务
	quit := make(chan os.Signal)
	signal.Notify(quit, syscall.SIGINT, syscall.SIGTERM)
	<-quit
	if err = register_client.DeRegister(serviceId); err != nil {
		fmt.Printf("【srv】注销失败:%s\n", err.Error())
	} else {
		fmt.Println("【srv】注销成功")
	}
}
